#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#include <poll.h>
#include <fcntl.h>
#include <assert.h>

#define BUFF_SIZE 64

int main(int argc, char const *argv[])
{
	const char* ip = "127.0.0.1";
	char* port = "9876";

	struct sockaddr_in serv_addr;
	bzero(&serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = PF_INET;
	serv_addr.sin_addr.s_addr = inet_addr(ip);
	serv_addr.sin_port = htons(atoi(port));

	int sock = socket(PF_INET, SOCK_STREAM, 0);
	assert(sock>=0);

	if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))<0){
		printf("connect erro\n");
		close(sock);
		return 1;
	}

	/*对标准输入0和sock上的可读事件进行监听*/
	struct pollfd fds[2];
	fds[0].fd = 0;
	fds[0].events = POLLIN;
	fds[0].revents = 0;
	fds[1].fd = sock;
	fds[1].events = POLLIN | POLLRDHUP;
	fds[1].revents = 0;

	char read_buf[BUFF_SIZE];
	int pipefd[2];
	int ret = pipe(pipefd);
	assert(ret!=-1);

	printf("please input:");
	while(1){
		ret = poll(fds, 2, -1);
		if(ret<0){
			printf("poll erro\n");
			break;
		}
		/*对所有文件描述符进行监听，只有2个不采用for循环*/
		if(fds[0].revents & POLLIN){
			//终端输入,发送给服务器
			ret = splice(0, NULL, pipefd[1], NULL, 
				BUFF_SIZE, SPLICE_F_MOVE | SPLICE_F_MORE);
			ret = splice(pipefd[0], NULL, sock, NULL, 
				BUFF_SIZE, SPLICE_F_MOVE | SPLICE_F_MORE);			
		}
		if(fds[1].revents & POLLIN){
			//服务器发送了数据，及时读取
			memset(read_buf, '\0', BUFF_SIZE);
			recv(fds[1].fd, read_buf, BUFF_SIZE, 0);
			printf("message from server:%s\n", read_buf);
			continue;
		}
		else if(fds[1].revents & POLLRDHUP){
			printf("server close the connection\n");
			break;
		}
	}
	close(sock);
	return 0;
}